package com.bwhx.eruler.controller.casdilly;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.bwhx.eruler.bean.Page;
import com.bwhx.eruler.bean.Staff;
import com.bwhx.eruler.bean.casdilly.CasdillyCustomer;
import com.bwhx.eruler.bean.casdilly.CasdillyScanData;
import com.bwhx.eruler.bean.casdilly.ClothesType;
import com.bwhx.eruler.controller.BaseController;
import com.bwhx.eruler.controller.WCController;
import com.bwhx.eruler.service.StaffService;
import com.bwhx.eruler.service.casdilly.CasdillyCustomerService;
import com.bwhx.eruler.service.casdilly.CasdillyScanDataService;
import com.bwhx.eruler.service.casdilly.ClothesTypeService;
import com.bwhx.eruler.service.hodo.ClothesSizeService;
import com.bwhx.eruler.util.Constant;
import com.bwhx.eruler.util.HttpUtil;
import com.bwhx.eruler.util.ListUtils;
import com.bwhx.eruler.util.ReadExcelUtil;
import com.bwhx.eruler.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/customer")
public class CasdillyCustomerController extends BaseController {

	@Autowired
	CasdillyCustomerService customerService;

	@Autowired
	CasdillyScanDataService casdillyScanDataService;

	@Autowired
	ClothesTypeService clothesTypeService;

	@Autowired
	WCController wCController;

	@Autowired
	StaffService staffService;

	String exportPath = "/home/bwhx/package/huamingcexls/";
//	String exportPath = "/Users/lm/home/bwhx/package/huamingcexls/";

	@ResponseBody
	@RequestMapping("/page.findByID.ashx")
	public CasdillyCustomer findByID(String customerID) {
		return customerService.findByID(customerID);

	}

	@ResponseBody
	@RequestMapping("/findByFenchangIDAndCreatorID.ashx")
	public HashMap<String, Object> findByFenchangIDAndCreatorID(HttpServletRequest request) {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		try {
			List<CasdillyCustomer> customerList = customerService.findByFenchangIDAndCreatorID(
					(String) request.getAttribute("lMIDFenChang"), (String) request.getAttribute("loginID"));
			//
			// for (int i = 0; i < customerList.size(); i++) {
			// String qRCodeURL = customerList.get(i).getqRCodeURL();
			// Date qRCodeURLCreateTime = customerList.get(i).getqRCodeURLCreateTime();
			// if(StringUtils.isEmpty(qRCodeURL)||new Date().getTime()/1000 -
			// qRCodeURLCreateTime.getTime()/1000>2592000*0.8){
			// String qrCodeURL =
			// wCController.getFromWXServer(Long.parseLong(customerList.get(i).getCustomerID()));
			// customerList.get(i).setqRCodeURL(qrCodeURL);
			// customerList.get(i).setqRCodeURLCreateTime(new Date());
			// //TODO
			// customerService.updateQrCodeInfo(customerList.get(i));
			// }
			// }

			resultMap.put(Constant.DATA, customerList);
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.MSG, Constant.MSG_SUCCESS);
		} catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			resultMap.put(Constant.MSG, Constant.MSG_FAIL);
		}

		return resultMap;
	}

	@ResponseBody
	@RequestMapping("/findUserDataByFenchangIDAndCreatorID.ashx")
	public HashMap<String, Object> findUserDataByFenchangIDAndCreatorID(HttpServletRequest request) {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		try {
			List<CasdillyCustomer> customerList = customerService.findUserDataByFenchangIDAndCreatorID(
					(String) request.getAttribute("lMIDFenChang"), (String) request.getAttribute("loginID"));

			/**
			 * 这里获取用户列表以及用户数据
			 */
			for (int i = 0; i < customerList.size(); i++) {
				CasdillyCustomer customer = customerList.get(i);
				List<CasdillyScanData> scanDataList = customerService
						.listScandataByCustomerID(customer.getCustomerID());
				if (scanDataList.size() > 0) {
					List<ClothesType> clothesTypeList = clothesTypeService
							.findByTypeCPIDSerial((String) request.getAttribute("lMIDContract"));
					List<HashMap<String, Object>> dataList = new ArrayList<>();
					for (int m = 0; m < clothesTypeList.size(); m++) {
						ClothesType clothesType = clothesTypeList.get(m);
						HashMap<String, Object> ClothesMap = new HashMap<String, Object>();
						HashMap<String, Object> tmpMap = new HashMap<String, Object>();
						for (int n = 0; n < scanDataList.size(); n++) {
							CasdillyScanData scanData = scanDataList.get(n);
							// 如果品类的名称相等
							if (clothesType.getTypeName().equals(scanData.getCategory())) {
								tmpMap.put(scanData.getTypename(), scanData.getShuzhi());
							}
						}
						ClothesMap.put(clothesType.getTypeName(), tmpMap);
						dataList.add(ClothesMap);
					}
					customerList.get(i).setUserScanData(dataList);
				}
			}

			resultMap.put(Constant.DATA, customerList);
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.MSG, Constant.MSG_SUCCESS);
		} catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			resultMap.put(Constant.MSG, Constant.MSG_FAIL);
		}
		return resultMap;
	}

	@ResponseBody
	@RequestMapping("/addCustomer.ashx")
	public HashMap<String, Object> addCustomer(HttpServletRequest request) {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		// JSONObject fromObject =
		// JSONObject.fromObject(request.getAttribute("CustomerInfo"));
		CasdillyCustomer customer = (CasdillyCustomer) JSONObject
				.toBean(JSONObject.fromObject(request.getAttribute("CustomerInfo")), CasdillyCustomer.class);
		log.info(customer);

		try {
			String cid = customerService.addCustomer(customer);
			resultMap.put(Constant.DATA, cid);
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.MSG, Constant.MSG_SUCCESS);
		} catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			resultMap.put(Constant.MSG, Constant.MSG_FAIL);
		}

		return resultMap;

	}
	@ResponseBody
	@RequestMapping("/updateCustomer.ashx")
	public HashMap<String, Object> updateCustomer(HttpServletRequest request) {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		// JSONObject fromObject =
		// JSONObject.fromObject(request.getAttribute("CustomerInfo"));
		CasdillyCustomer customer = (CasdillyCustomer) JSONObject
				.toBean(JSONObject.fromObject(request.getAttribute("CustomerInfo")), CasdillyCustomer.class);
		log.info(customer);

		try {
			// customerService 存储
			customerService.updateCustomer(customer, null);
			resultMap.put(Constant.DATA, customer.getCustomerID());
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.MSG, Constant.MSG_SUCCESS);
		} catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			resultMap.put(Constant.MSG, Constant.MSG_FAIL);
		}

		return resultMap;

	}

	@ResponseBody
	@RequestMapping("/uploadFileCustomerPic.ashx")
	public HashMap<String, Object> uploadFile(
			@RequestParam(value = "cPhotoZM", required = false) CommonsMultipartFile cPhotoZM,
			@RequestParam(value = "cPhotoCM", required = false) CommonsMultipartFile cPhotoCM,
			@RequestParam(value = "cPhotoBM", required = false) CommonsMultipartFile cPhotoBM,
			@RequestParam(value = "cPhotoQM", required = false) CommonsMultipartFile cPhotoQM,
			@RequestParam(value = "token", required = true) String token,
			@RequestParam(value = "ip", required = true) String ipAddress,
			@RequestParam(value = "customerID", required = false) String customerID, HttpServletRequest request) {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		HashMap<String, String> dataMap = new HashMap<String, String>();

		if (!token.equals("123wfzaaSD*")) {
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			resultMap.put(Constant.MSG, "非法访问");
			return resultMap;
		}

		if (StringUtils.isEmpty(customerID)) {
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			resultMap.put(Constant.MSG, "customerID不能为空");
			return resultMap;
		}
		if (StringUtils.isEmpty(ipAddress)) {
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			resultMap.put(Constant.MSG, "ip不能为空");
			return resultMap;
		}

		CasdillyCustomer customer = customerService.findByID(customerID);

		if (null == customer) {
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			resultMap.put(Constant.MSG, "customerID没找到用户");
			return resultMap;
		}
//		String customerName = customer.getCustomerName();

		long time = new Date().getTime();
		try {
			Client client = null;

			String imgPath = String.format("http://%s:%s%s%s", ipAddress, request.getLocalPort(),
					request.getContextPath(), Constant.CASDILLY_FULLPATH);
			if (null != cPhotoZM && cPhotoZM.getSize() != 0) {
				String ss = request.getHeader("");
				client = Client.create();
				String zMName = time  + cPhotoZM.getOriginalFilename();
				byte[] zMByte = cPhotoZM.getBytes();
				WebResource webResource = client
						.resource(String.format("%s/%s", imgPath, URLEncoder.encode(zMName, "utf-8")));
				webResource.put(String.class, zMByte);
				dataMap.put("cPhotoZM", String.format("%s/%s", imgPath, zMName));
			}

			if (null != cPhotoCM && cPhotoCM.getSize() != 0) {
				String cMName = time  + cPhotoCM.getOriginalFilename();
				byte[] cMByte = cPhotoCM.getBytes();

				if (client == null) {
					client = Client.create();
				}
				WebResource webResource = client
						.resource(String.format("%s/%s", imgPath, URLEncoder.encode(cMName, "utf-8")));
				webResource.put(String.class, cMByte);
				dataMap.put("cPhotoCM", String.format("%s/%s", imgPath, cMName));
			}

			if (null != cPhotoBM && cPhotoBM.getSize() != 0) {
				String bMName = time  + cPhotoBM.getOriginalFilename();
				byte[] bMByte = cPhotoBM.getBytes();

				if (client == null) {
					client = Client.create();
				}
				WebResource webResource = client
						.resource(String.format("%s/%s", imgPath, URLEncoder.encode(bMName, "utf-8")));
				webResource.put(String.class, bMByte);
				dataMap.put("cPhotoBM", imgPath + bMName);
			}

			if (null != cPhotoQM && cPhotoQM.getSize() != 0) {
				String qMName = time  + cPhotoQM.getOriginalFilename();
				byte[] qMByte = cPhotoQM.getBytes();

				if (client == null) {
					client = Client.create();
				}
				WebResource webResource = client
						.resource(String.format("%s/%s", imgPath, URLEncoder.encode(qMName, "utf-8")));
				webResource.put(String.class, qMByte);
				dataMap.put("cPhotoQM", String.format("%s/%s", imgPath, qMName));
			}

			if (dataMap.size() > 0) {
				dataMap.put("customerID", customerID);
				resultMap.put(Constant.DATA, dataMap);
				customerService.updateCustomerPic(dataMap);
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.MSG, Constant.MSG_SUCCESS);

			} else {
				resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
				resultMap.put(Constant.MSG, "未发现文件");
			}

		} catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			resultMap.put(Constant.MSG, Constant.MSG_FAIL);
		}

		return resultMap;

	}

	@ResponseBody
	@RequestMapping("/commitScanData.ashx")
	public HashMap<String, Object> commitScanData(HttpServletRequest request) {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();

		try {
			CasdillyCustomer customer = (CasdillyCustomer) JSONObject
					.toBean(JSONObject.fromObject(request.getAttribute("user_info")), CasdillyCustomer.class);
			log.info(customer);

			String jsonStr = new String();
			// 因为传上来的cScanData json 与数据库存储的字段不一致，所以手动解析json存储到数据库
			Object scandatainfoAttribute = request.getAttribute("scandata_info");
			LinkedHashMap<String, LinkedHashMap<String, String>> scandataMap = new LinkedHashMap<String, LinkedHashMap<String, String>>();
			if (scandatainfoAttribute instanceof String) {
				ObjectMapper objectMapper = new ObjectMapper();
				scandataMap = objectMapper.readValue(scandatainfoAttribute.toString(), LinkedHashMap.class);

			} else {
				scandataMap = (LinkedHashMap<String, LinkedHashMap<String, String>>) request
						.getAttribute("scandata_info");

			}

			List<CasdillyScanData> cScanDataList = new ArrayList<CasdillyScanData>();
			for (Map.Entry<String, LinkedHashMap<String, String>> entry : scandataMap.entrySet()) {
				String key = entry.getKey();
				LinkedHashMap<String,String> map = scandataMap.get(key);
				for (Map.Entry<String, String> subEntry : map.entrySet()) {
					if (subEntry.getKey() != null && subEntry.getValue() != null) {
						cScanDataList.add(new CasdillyScanData(customer.getCustomerID(), key, subEntry.getKey(),
								subEntry.getValue()));
					}
				}

			}

			CasdillyCustomer isCustomer = customerService.get(customer.getCustomerID());
			if (isCustomer == null) {
				resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
				resultMap.put(Constant.MSG, "没有找到该用户。");
				return resultMap;
			} /*
				 * else if(null!=isCustomer.getExportstatus()){ resultMap.put(Constant.STATUS,
				 * Constant.STATUS_FAIL); resultMap.put(Constant.MSG,
				 * isCustomer.getCustomerName()+"用户已经导出。"); return resultMap; }
				 */
			// customerService 存储
			customerService.updateCustomer(customer, cScanDataList);

			resultMap.put(Constant.DATA, customer.getCustomerID());
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.MSG, Constant.MSG_SUCCESS);
		} catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			resultMap.put(Constant.MSG, Constant.MSG_FAIL);
		}

		return resultMap;

	}

	@ResponseBody
	@RequestMapping(value = "/page.list.ashx")
	public Map<String, Object> ctList(Integer page, Integer rows, CasdillyCustomer ct, HttpSession session) {

		Staff staff = (Staff) session.getAttribute("staff");
		if (null == staff.getUserType() || 1 != staff.getUserType()) {
			ct.setCreatorID(staff.getsId().toString());
		}

		// 每页的开始记录
		int start = (page - 1) * rows;
		Page p = new Page(start, rows, ct);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			List<CasdillyCustomer> list = customerService.list(p);
			Integer count = customerService.count(ct);
			resultMap.put("total", count);// total键 存放总记录数，必须的
			resultMap.put("rows", list);// rows键 存放每页记录 list

		} catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put("msg", "失败！");
			resultMap.put("status", "0");
		}
		return resultMap;
	}

	@ResponseBody
	@RequestMapping(value = "/page.uploadHuaMingCe.ashx", method = RequestMethod.POST)
	public HashMap<String, Object> uploadPic(String fenchangid, HttpSession session,
			@RequestParam(value = "huamingce", required = false) CommonsMultipartFile file,
			HttpServletRequest request) {

		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		try {

			String fileName = file.getOriginalFilename();
			String extension = fileName.lastIndexOf(".") == -1 ? "" : fileName.substring(fileName.lastIndexOf(".") + 1);
			if (!"xls".equals(extension)) {
				resultMap.put("msg", "仅支持后缀为xls的Excel电子表格，若是您定的后缀为xlsx，请另存为xls！");
				resultMap.put("status", "0");
			}
			Staff staff = (Staff) session.getAttribute("staff");
			String sLoginName = staff.getsLoginName();

			if (!file.isEmpty()) {

				// 存储在本地

				String filePath = exportPath + sLoginName + "_" + new Date().getTime() + "_" + fileName;
				String os = System.getProperty("os.name");
				if (os.toLowerCase().startsWith("win")) {
					filePath = StringUtils.GetRootPath(request) + "/home/bwhx/package/huamingcexls/" + sLoginName + "_"
							+ new Date().getTime() + "_" + fileName;

				}

				File ioFile = new File(filePath);
				file.transferTo(ioFile);

				// 使用xls解析

				HashMap<String, Object> readExcelReslutMap = ReadExcelUtil.readExcel(ioFile, staff.getsId(),
						fenchangid);
				String status = (String) readExcelReslutMap.get("status");
				if (status.equals("0")) {
					return readExcelReslutMap;
				} else {
					LinkedList<CasdillyCustomer> customerList = (LinkedList<CasdillyCustomer>) readExcelReslutMap
							.get("data");

					// 用户判重
					for (CasdillyCustomer casdillyCustomer : customerList) {
						CasdillyCustomer resultCustomer = customerService.findByFenchangIDAndUserName(casdillyCustomer);
						if (resultCustomer != null) {
							resultMap.put("msg", "上传失败！<br><br>" + "当前分场下已经存在用户:<br><br>【"
									+ resultCustomer.getCustomerName() + "】<br><br>上传人为【"
									+ resultCustomer.getV_creatorName() + "】<br><br>上传时间为【"
									+ new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(resultCustomer.getCreateTime())
									+ "】<br><br>请检查是否导入了重复的花名册！");
							resultMap.put("status", "0");
							return resultMap;
						}
					}

					Boolean b = insertIntoDB(customerList);
					if (b) {
						resultMap.put("msg", "上传成功了" + customerList.size() + "条数据，请点击查看花名册查看。");
						resultMap.put("status", "1");
					} else {
						resultMap.put("msg", "失败！");
						resultMap.put("status", "0");
					}

				}

			} else {
				resultMap.put("msg", "文件为空！");
				resultMap.put("status", "0");
			}
		} catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put("msg", "失败！");
			resultMap.put("status", "0");
		}

		return resultMap;
	}

	private Boolean insertIntoDB(LinkedList<CasdillyCustomer> customerList) {

		return customerService.insert(customerList);
	}

	@ResponseBody
	@RequestMapping(value = "/page.listByHTSerial.ashx")
	public Map<String, Object> listByHTSerial(Integer page, Integer rows, CasdillyCustomer customer) {

		Staff sessionStaff = this.getSessionStaff();
		if (null == sessionStaff.getUserType() || 1 != sessionStaff.getUserType()) {
			customer.setCreatorID(sessionStaff.getsId().toString());
		}

		// 每页的开始记录
		int start = (page - 1) * rows;
		Page p = new Page(start, rows, customer);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {

			log.info(StringUtils.PrintCurrentDateTime("开始查询"));
			List<Map<String, String>> list = customerService.listByHetongSerial(p);
			log.info(StringUtils.PrintCurrentDateTime("结束查询"));
			Integer count = customerService.countByHetongSerial(customer); //

			resultMap.put("total", count);// total键 存放总记录数，必须的
			resultMap.put("rows", list);// rows键 存放每页记录 list

		} catch (Exception e) {
			try {
				log.error(getTrace(e));
			} catch (Exception ex) {

			}
			resultMap.put("msg", String.format("失败，原因:%s", e.getMessage()));
			resultMap.put("status", "0");
		}

		return resultMap;
	}

	@ResponseBody
	@RequestMapping(value = "/page.exportdata.ashx")
	public void exportdata(CasdillyCustomer customer, HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {

		Staff sessionStaff = this.getSessionStaff();
		if (null == sessionStaff.getUserType() || 1 != sessionStaff.getUserType()) {
			customer.setCreatorID(sessionStaff.getsId().toString());
		}

		// ！准备表头数据
		String[] tableHeaderArray = { "新序号", "原序号", "归属", "单位", "部门", "姓名", "性别", "身高", "头围", "领围", "净胸围", "中腰", "净腰围",
				"净臀围", "裤长", "横档", "直档", "肩宽", "袖长", "前衣长", "鞋号", "自报或套穿上衣号型", "上衣附加", "自报下裤号型", "备注一", "备注二", "备注三",
				"体重Kg", "喜好合适", "喜好宽松", "喜好修身" };
		ArrayList<String> tableHeaderList = new ArrayList<String>(Arrays.asList(tableHeaderArray));

		List<ClothesType> clothesTypeList = clothesTypeService.findByTypeCPIDSerial(customer.getHetongSerial());
		for (ClothesType clothesType : clothesTypeList) {
			String typeName = clothesType.getTypeName();
			tableHeaderList.add(typeName + "号型");
			tableHeaderList.add(typeName + "数量");
		}
		// ！准备内容数据
		List<Map<String, String>> list = customerService.listByHetongSerial(customer);

		// ！初始化excel表，写表头
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook();// 1、 工作薄 （Excel文档 ）
		HSSFSheet sheet = hssfWorkbook.createSheet("测量数据");// 2、写一个sheet
		HSSFRow row = null; // 3、定义row
		HSSFCell cell = null; // 4、 定义cell
		int rowCounter = 0;

		if (rowCounter == 0) {
			row = sheet.createRow(rowCounter);
			for (int i = 0; i < tableHeaderList.size(); i++) {
				cell = row.createCell(i);
				cell.setCellValue(tableHeaderList.get(i));

			}
			rowCounter++;
		}

		// !写内容
		for (Map<String, String> map : list) {
			row = sheet.createRow(rowCounter);
			for (int i = 0; i < tableHeaderList.size(); i++) {
				cell = row.createCell(i);

				if (i == 0)
					cell.setCellValue(rowCounter); // 新序号
				else if (i == 1)
					cell.setCellValue(map.get("customerIndex"));// 原序号
				else if (i == 2)
					cell.setCellValue("");// 归属?
				else if (i == 3)
					cell.setCellValue(map.get("customerCom"));// 单位
				else if (i == 4)
					cell.setCellValue(map.get("customerDep"));// 部门
				else if (i == 5)
					cell.setCellValue(map.get("customerName"));// 姓名
				else if (i == 6)
					cell.setCellValue("0".equals(map.get("customerSex")) ? "男" : "女");// 性别
				else if (i > 6 && i < 21)
					cell.setCellValue(map.get(tableHeaderList.get(i)));// 身高
				else if (i == 21)
					cell.setCellValue("");// 自报或套穿上衣号型?
				else if (i == 22)
					cell.setCellValue("");// 上衣附加?
				else if (i == 23)
					cell.setCellValue("");// 自报下裤号型?
				else if (i == 24)
					cell.setCellValue("");// 备注一?
				else if (i == 25)
					cell.setCellValue("");// 备注二?
				else if (i == 26)
					cell.setCellValue(map.get("customerBeiZhu"));// 备注三
				else if (i == 27)
					cell.setCellValue(map.get("体重"));// 体重？体重，身高是应该放在品类数据中还是放在客户基本属性中？？？
				else if (i == 28)
					cell.setCellValue("舒适".equals(map.get("穿衣风格")) ? "√" : "");// App中着装偏好为输入框而不是选择框！！！！？？？
				else if (i == 29)
					cell.setCellValue("宽松".equals(map.get("穿衣风格")) ? "√" : "");// App中着装偏好为输入框而不是选择框！！！！？？？
				else if (i == 30)
					cell.setCellValue("修身".equals(map.get("穿衣风格")) ? "√" : "");// App中着装偏好为输入框而不是选择框！！！！？？？
				else if (i > 30) {

					if (i % 2 == 1) {
						// 品类号型
						cell.setCellValue(map.get(tableHeaderList.get(i)));// 品类号型，使用人工判号值？？？？？？？？

					} else {
						cell.setCellValue("");// 品类件数无处可取？？？
					}
				}

			}
			rowCounter++;
		}

		// ! 5、将Excel 保存到硬盘

		String linuxPartName = "全部用户_由";

		if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_1")) {
			linuxPartName = "已量用户_由";

		} else if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_null")) {
			linuxPartName = "未量用户_由";
		}

		String filePath = exportPath + customer.getHetongSerial() + linuxPartName + this.getSessionStaff().getsName()
				+ "于" + new SimpleDateFormat("YYYY年MM月dd日HH时mm分").format(new Date()) + "导出.xls";
		String os = System.getProperty("os.name");
		if (os.toLowerCase().startsWith("win")) {
			String partName = "全部用户】_【";

			if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_1")) {
				partName = "已量用户】_【";

			} else if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_null")) {
				partName = "未量用户】_【";
			}
			filePath = StringUtils.GetRootPath(request) + "/home/bwhx/package/huamingcexls/【"
					+ customer.getHetongSerial() + partName + this.getSessionStaff().getsName() + "】_【"
					+ new SimpleDateFormat("YYYY年MM月dd日HH时mm分ss秒").format(new Date()) + "】.xls";

		}
		FileOutputStream fileOutputStream = new FileOutputStream(filePath);

		hssfWorkbook.write(fileOutputStream);
		fileOutputStream.close();

		File file = new File(filePath);
		String filename = file.getName();
		// 以流的形式下载文件。
		InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
		byte[] buffer = new byte[fis.available()];
		fis.read(buffer);
		fis.close();

		response.reset();
		// 设置response的Header
		String string = new String(filename.getBytes());
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
		response.addHeader("Content-Length", "" + file.length());
		OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		toClient.write(buffer);
		toClient.flush();
		toClient.close();
		customerService.updateCustomerExportStatus(list, this.getSessionStaff().getsId(), new Date());
	}

	@ResponseBody
	@RequestMapping(value = "/page.exportCheckedData.ashx")
	public void exportCheckedData(String ids, String hetongSerial, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// ！准备表头数据
		String[] tableHeaderArray = { "新序号", "原序号", "归属", "单位", "部门", "姓名", "性别", "身高", "头围", "领围", "净胸围", "中腰", "净腰围",
				"净臀围", "裤长", "横档", "直档", "肩宽", "袖长", "前衣长", "鞋号", "自报或套穿上衣号型", "上衣附加", "自报下裤号型", "备注一", "备注二", "备注三",
				"体重Kg", "喜好合适", "喜好宽松", "喜好修身" };
		ArrayList<String> tableHeaderList = new ArrayList<String>(Arrays.asList(tableHeaderArray));

		List<ClothesType> clothesTypeList = clothesTypeService.findByTypeCPIDSerial(hetongSerial);
		for (ClothesType clothesType : clothesTypeList) {
			String typeName = clothesType.getTypeName();
			tableHeaderList.add(typeName + "号型");
			tableHeaderList.add(typeName + "数量");
		}

		// ！准备内容数据
		List<Map<String, String>> list = customerService.listByIDs(ids);

		// ！初始化excel表，写表头
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook();// 1、 工作薄 （Excel文档 ）
		HSSFSheet sheet = hssfWorkbook.createSheet("测量数据");// 2、写一个sheet
		HSSFRow row = null; // 3、定义row
		HSSFCell cell = null; // 4、 定义cell
		int rowCounter = 0;

		if (rowCounter == 0) {
			row = sheet.createRow(rowCounter);
			for (int i = 0; i < tableHeaderList.size(); i++) {
				cell = row.createCell(i);
				cell.setCellValue(tableHeaderList.get(i));

			}
			rowCounter++;
		}

		// !写内容
		for (Map<String, String> map : list) {
			row = sheet.createRow(rowCounter);
			for (int i = 0; i < tableHeaderList.size(); i++) {
				cell = row.createCell(i);

				if (i == 0)
					cell.setCellValue(rowCounter); // 新序号
				else if (i == 1)
					cell.setCellValue(map.get("customerIndex"));// 原序号
				else if (i == 2)
					cell.setCellValue("");// 归属?
				else if (i == 3)
					cell.setCellValue(map.get("customerCom"));// 单位
				else if (i == 4)
					cell.setCellValue(map.get("customerDep"));// 部门
				else if (i == 5)
					cell.setCellValue(map.get("customerName"));// 姓名
				else if (i == 6)
					cell.setCellValue("0".equals(map.get("customerSex")) ? "男" : "女");// 性别
				else if (i > 6 && i < 21)
					cell.setCellValue(map.get(tableHeaderList.get(i)));// 身高
				else if (i == 21)
					cell.setCellValue("");// 自报或套穿上衣号型?
				else if (i == 22)
					cell.setCellValue("");// 上衣附加?
				else if (i == 23)
					cell.setCellValue("");// 自报下裤号型?
				else if (i == 24)
					cell.setCellValue("");// 备注一?
				else if (i == 25)
					cell.setCellValue("");// 备注二?
				else if (i == 26)
					cell.setCellValue(map.get("customerBeiZhu"));// 备注三
				else if (i == 27)
					cell.setCellValue(map.get("体重"));// 体重？体重，身高是应该放在品类数据中还是放在客户基本属性中？？？
				else if (i == 28)
					cell.setCellValue("舒适".equals(map.get("穿衣风格")) ? "√" : "");// App中着装偏好为输入框而不是选择框！！！！？？？
				else if (i == 29)
					cell.setCellValue("宽松".equals(map.get("穿衣风格")) ? "√" : "");// App中着装偏好为输入框而不是选择框！！！！？？？
				else if (i == 30)
					cell.setCellValue("修身".equals(map.get("穿衣风格")) ? "√" : "");// App中着装偏好为输入框而不是选择框！！！！？？？
				else if (i > 30) {

					if (i % 2 == 1) {
						// 品类号型
						cell.setCellValue(map.get(tableHeaderList.get(i)));// 品类号型，使用人工判号值？？？？？？？？

					} else {
						cell.setCellValue("");// 品类件数无处可取？？？
					}
				}

			}
			rowCounter++;
		}

		// ! 5、将Excel 保存到硬盘

		String linuxPartName = "选中用户_由";

		String filePath = exportPath + linuxPartName + this.getSessionStaff().getsName() + "于"
				+ new SimpleDateFormat("YYYY年MM月dd日HH时mm分").format(new Date()) + "导出.xls";
		String os = System.getProperty("os.name");
		if (os.toLowerCase().startsWith("win")) {
			String partName = "选中用户】_【";
			filePath = StringUtils.GetRootPath(request) + "/home/bwhx/package/huamingcexls/【" + hetongSerial + partName
					+ this.getSessionStaff().getsName() + "】_【"
					+ new SimpleDateFormat("YYYY年MM月dd日HH时mm分ss秒").format(new Date()) + "】.xls";

		}

		FileOutputStream fileOutputStream = new FileOutputStream(filePath);

		hssfWorkbook.write(fileOutputStream);
		fileOutputStream.close();

		File file = new File(filePath);
		String filename = file.getName();
		// 以流的形式下载文件。
		InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
		byte[] buffer = new byte[fis.available()];
		fis.read(buffer);
		fis.close();

		response.reset();
		// 设置response的Header
		String string = new String(filename.getBytes());
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
		response.addHeader("Content-Length", "" + file.length());
		OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		toClient.write(buffer);
		toClient.flush();
		toClient.close();
		customerService.updateCustomerExportStatus(list, this.getSessionStaff().getsId(), new Date());
	}

	@ResponseBody
	@RequestMapping(value = "/page.everyone.listByPhone.ashx")
	public Map<String, Object> listByPhone(CasdillyCustomer ct) {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		try {
			if (StringUtils.isEmpty(ct.getCustomerTel())) {
				resultMap.put("status", "0");
			} else {
				List<CasdillyCustomer> list = customerService.listByPhone(ct);
				resultMap.put("data", list);// rows键 存放每页记录 list
				resultMap.put("status", "1");
			}

		} catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put("msg", "失败！");
			resultMap.put("status", "0");
		}

		return resultMap;
	}

	@ResponseBody
	@RequestMapping(value = "/page.everyone.queryScanDataByCustomerId.ashx")
	public Map<String, Object> phoneScandataList(CasdillyCustomer customer) {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		try {
			CasdillyCustomer customerByID = customerService.getCustomerAndScanData(customer.getCustomerID());

			if (null == customerByID) {
				resultMap.put("status", "0");
				resultMap.put("msg", "未找到用户！");

			} else {
				List<CasdillyScanData> scandata = customerByID.getScandata();

				if (scandata.size() > 1) {
					String stature = "";
					String weight = "";
					for (CasdillyScanData casdillyScanData : scandata) {
						if (casdillyScanData.getTypename().equals("身高")) {
							stature = casdillyScanData.getShuzhi();
						}
						if (casdillyScanData.getTypename().equals("体重")) {
							weight = casdillyScanData.getShuzhi();
						}

					}

					if (!(stature.equals("") || weight.equals(""))) {
						customerByID.setBmiTest(bmiTest(stature, weight));
					}
				}
				resultMap.put("data", customerByID);
				resultMap.put("status", "1");

				Map<String, List<CasdillyScanData>> scandataMap = new HashMap<String, List<CasdillyScanData>>();
				for (CasdillyScanData casdillyScanData : scandata) {

					if (casdillyScanData.getTypename().equals("体重")) {
						casdillyScanData.setShuzhi(casdillyScanData.getShuzhi().split("_")[0] + "kg");
					} else if (casdillyScanData.getShuzhi().split("_").length == 1) {

					} else {
						casdillyScanData.setShuzhi(casdillyScanData.getShuzhi().split("_")[0] + "cm");
					}

					String category = casdillyScanData.getCategory();

					if (scandataMap.containsKey(category)) {
						List<CasdillyScanData> list = scandataMap.get(category);
						list.add(casdillyScanData);
						scandataMap.put(category, list);
					} else {
						List<CasdillyScanData> list = new ArrayList<CasdillyScanData>();
						list.add(casdillyScanData);
						scandataMap.put(category, list);
					}
				}

				resultMap.put("scandataMap", scandataMap);

			}

		} catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put("status", "0");
			resultMap.put("msg", "失败！");
		}

		return resultMap;
	}

	private String bmiTest(String stature, String weight) {
		String bodyMassIndexComment = "";

		if (!stature.contains(".")) {
			stature += ".00";
		}
		if (!weight.contains(".")) {
			weight += ".00";
		}
		BigDecimal statureBigDecimal = new BigDecimal(stature.split("_")[0]);
		BigDecimal weightBigDecimal = new BigDecimal(weight.split("_")[0]);
		BigDecimal statureM = statureBigDecimal.divide(new BigDecimal("100.00"));

		BigDecimal divide = weightBigDecimal.divide(statureM.multiply(statureM), 1);
		double bodyMassIndexDoubleValue = divide.doubleValue();
		String bodyMassIndex = new DecimalFormat("#.0").format(bodyMassIndexDoubleValue);
		if (bodyMassIndexDoubleValue != 0.0) {
			if (bodyMassIndexDoubleValue >= 40) {// 极重度肥胖 相关疾病发病危险性（非常严重增加）
				bodyMassIndexComment = "BMI健康评测： 您的BMI指数" + bodyMassIndex + "，极重度肥胖。 相关疾病发病危险性：非常严重增加。";
			} else if (bodyMassIndexDoubleValue >= 30) {// 重度肥胖 相关疾病发病危险性（严重增加）
				bodyMassIndexComment = "BMI健康评测： 您的BMI指数" + bodyMassIndex + "，重度肥胖。相关疾病发病危险性：严重增加。";

			} else if (bodyMassIndexDoubleValue >= 28) {// 肥胖 相关疾病发病危险性（中度增加）
				bodyMassIndexComment = "BMI健康评测： 您的BMI指数" + bodyMassIndex + "，肥胖。\n相关疾病发病危险性：中度增加。";
			} else if (bodyMassIndexDoubleValue >= 24 && bodyMassIndexDoubleValue < 28) {// 超重 相关疾病发病危险性（增加）
				bodyMassIndexComment = "BMI健康评测： 您的BMI指数" + bodyMassIndex + "，超重。\n相关疾病发病危险性：增加。";
			} else if (bodyMassIndexDoubleValue >= 18.5 && bodyMassIndexDoubleValue < 24) {// 正常 相关疾病发病危险性（平均水平）
				bodyMassIndexComment = "BMI健康评测： 您的BMI指数" + bodyMassIndex + "，正常。\n相关疾病发病危险性：平均水平。";

			} else if (bodyMassIndexDoubleValue < 18.5) {// 偏瘦 相关疾病发病危险性（低（但其他疾病危险性增加））
				bodyMassIndexComment = "BMI健康评测： 您的BMI指数" + bodyMassIndex + "，偏瘦。\n相关疾病发病危险性：低（但其他疾病危险性增加）。";
			}
		}
		return bodyMassIndexComment;
	}

	@ResponseBody
	@RequestMapping(value = "/page.listScandataByID.ashx")
	public Map<String, Object> ctList(Integer page, Integer rows, String customerID) {

		// 每页的开始记录
		int start = (page - 1) * rows;
		Page p = new Page(start, rows, customerID);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			List<CasdillyScanData> list = customerService.listScandataByID(p);
			Integer count = customerService.countScandataByID(customerID);

			resultMap.put("total", count);// total键 存放总记录数，必须的
			resultMap.put("rows", list);// rows键 存放每页记录 list

		} catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put("msg", "失败！");
			resultMap.put("status", "0");
		}

		return resultMap;
	}

	@ResponseBody
	@RequestMapping(value = "/page.updateScandata.ashx")
	public String saveOrUpdate(CasdillyScanData csd) {
		try {

			customerService.updateScandata(csd);

		} catch (Exception e) {
			log.error(getTrace(e));
			return "fail";
		}

		return "success";
	}

	@ResponseBody
	@RequestMapping(value = "/page.everyone.findCustomerNameById.ashx")
	public CasdillyCustomer findCustomerById(String customerID) {
		CasdillyCustomer findCustomerById = customerService.findCustomerNameById(customerID);

		log.info(findCustomerById);

		return findCustomerById;
	}

	@RequestMapping(value = "/page.everyone.updateCustomerOpenID.ashx")
	public void updateCustomerOpenID(CasdillyCustomer customer) {
		customerService.updateCustomerOpenID(customer);

	}

	@ResponseBody
	@RequestMapping(value = "/page.everyone.getCustomerHistoryEventItem.ashx")
	public Map<String, Object> getCustomerHistoryEventItem(String code) {

		if (code.equals("-1")) {
			Map<String, Object> listBywxOpenid = listBywxOpenid("o6nppuHulCGAQuKes0AFvWnoAhX0");
			return listBywxOpenid;

		}

		Map<String, Object> resultMap = new HashMap<String, Object>();

		try {
			/*
			 * if(StringUtils.isEmpty(ct.getCustomerTel())){ resultMap.put("status", "0");
			 * }else{ List<CasdillyCustomer> list = customerService.listByPhone(ct);
			 * resultMap.put("data",list);//rows键 存放每页记录 list resultMap.put("status", "1");
			 * }
			 */

			String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constant.WX_ID + "&secret="
					+ Constant.WX_SECRET + "&code=" + code + "&grant_type=authorization_code";

			String wxResponse = HttpUtil.sendGet(url);
			JSONObject jsonObject = JSONObject.fromObject(wxResponse);
			String wxOpenid = jsonObject.getString("openid");
			Map<String, Object> listBywxOpenid = listBywxOpenid(wxOpenid);

			return listBywxOpenid;

		} catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put("msg", "失败！");
			resultMap.put("status", "0");
		}

		return resultMap;
	}

	@ResponseBody
	@RequestMapping(value = "/page.everyone.listBywxOpenid.ashx")
	public Map<String, Object> listBywxOpenid(String wxOpenid) {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		try {

			List<CasdillyCustomer> list = customerService.listBywxOpenid(wxOpenid);

			for (CasdillyCustomer casdillyCustomer : list) {
				CasdillyCustomer customerAndScanData = customerService
						.getCustomerAndScanData(casdillyCustomer.getCustomerID());
				List<CasdillyScanData> scandata = customerAndScanData.getScandata();
				StringBuilder v_pinleiStr = new StringBuilder();
				HashSet<String> hashSet = new HashSet<String>();
				for (CasdillyScanData casdillyScanData : scandata) {
					String category = casdillyScanData.getCategory();
					hashSet.add(category);
				}
				for (String string : hashSet) {
					v_pinleiStr.append(string).append(",");
				}
				String substring = v_pinleiStr.substring(0, v_pinleiStr.length() - 1);

				casdillyCustomer.setV_pinleimingStr(substring);

			}

			resultMap.put("status", "1");
			resultMap.put("data", list);

		} catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put("msg", "失败！");
			resultMap.put("status", "0");
		}

		return resultMap;
	}

	@Autowired
	ClothesSizeService csService;

	@ResponseBody
	@RequestMapping(value = "/page.hodo_exportdata.ashx")
	public void HodoExportdata(CasdillyCustomer customer, HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {

		Staff sessionStaff = this.getSessionStaff();
		if (null == sessionStaff.getUserType() || 1 != sessionStaff.getUserType()) {
			customer.setCreatorID(sessionStaff.getsId().toString());
		}

		// 获取品类信息，成衣信息

		// 品类信息
		List<ClothesType> clothesTypeList = clothesTypeService.findByTypeCPIDSerial(customer.getHetongSerial());

		// 成衣信息
		HashMap<String, Object> csdMap = new HashMap<String, Object>();

		for (ClothesType clothesType : clothesTypeList) {

			if (null != clothesType.getClothesSizeID()) {
				List<Map<String, String>> csdList = csService.findByClothesSizeID(clothesType.getClothesSizeID());
				csdMap.put(clothesType.getTypeName(), csdList);
			}

		}

		// 获取用户信息 和测量数据信息
		List<CasdillyCustomer> customerList = customerService.hodoListByHetongSerial(customer);

		// ！准备表头数据
		String[] tableHeaderArray = { "编号", "姓名", "性别", "年龄", "公司", "部门", "电话", "上衣号衣", "下衣号衣", "单位", "净体尺寸", "成衣尺寸",
				"修正量", "备注", "正面照", "背面照", "侧面照", "客户签名" };
		ArrayList<String> tableHeaderList = new ArrayList<String>(Arrays.asList(tableHeaderArray));

		// 初始化excel
		HSSFWorkbook initExcel = initExcel(tableHeaderList, customerList, clothesTypeList, csdMap);

		// 获取图片资料并压缩

		// response 返回

		// ! 5、将Excel 保存到硬盘

		String linuxPartName = "全部用户_由";

		if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_1")) {
			linuxPartName = "已量用户_由";

		} else if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_null")) {
			linuxPartName = "未量用户_由";
		}

		String filePath = exportPath + customer.getHetongSerial() + linuxPartName + this.getSessionStaff().getsName()
				+ "于" + new SimpleDateFormat("YYYY年MM月dd日HH时mm分").format(new Date()) + "导出.xls";
		String os = System.getProperty("os.name");
		if (os.toLowerCase().startsWith("win")) {
			String partName = "全部用户】_【";

			if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_1")) {
				partName = "已量用户】_【";

			} else if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_null")) {
				partName = "未量用户】_【";
			}
			filePath = StringUtils.GetRootPath(request) + "/home/bwhx/package/huamingcexls/【"
					+ customer.getHetongSerial() + partName + this.getSessionStaff().getsName() + "】_【"
					+ new SimpleDateFormat("YYYY年MM月dd日HH时mm分ss秒").format(new Date()) + "】.xls";

		}
		FileOutputStream fileOutputStream = new FileOutputStream(filePath);

		initExcel.write(fileOutputStream);
		fileOutputStream.close();

		File file = new File(filePath);
		String filename = file.getName();
		// 以流的形式下载文件。
		InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
		byte[] buffer = new byte[fis.available()];
		fis.read(buffer);
		fis.close();

		response.reset();
		// 设置response的Header
		String string = new String(filename.getBytes());
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
		response.addHeader("Content-Length", "" + file.length());
		OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		toClient.write(buffer);
		toClient.flush();
		toClient.close();
		// TODO
		// customerService.updateCustomerExportStatus(customerList,this.getSessionStaff().getsId(),new
		// Date());
	}

	private HSSFWorkbook initExcel(ArrayList<String> tableHeaderList, List<CasdillyCustomer> customerList,
			List<ClothesType> clothesTypeList, HashMap<String, Object> csdMap) {
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook();// 1、 工作薄 （Excel文档 ）

		for (int sheetCounter = 0; sheetCounter < clothesTypeList.size(); sheetCounter++) {

			// ！初始化excel表，写表头
			String typeName = clothesTypeList.get(sheetCounter).getTypeName();
			HSSFSheet sheet = hssfWorkbook.createSheet(typeName);// 2、写一个sheet
			HSSFRow row = null; // 3、定义row
			HSSFCell cell = null; // 4、 定义cell
			int rowCounter = 0;

			if (rowCounter == 0) {
				row = sheet.createRow(rowCounter);
				for (int cellCounter = 0; cellCounter < tableHeaderList.size(); cellCounter++) {
					cell = row.createCell(cellCounter);
					cell.setCellValue(tableHeaderList.get(cellCounter));

				}
				rowCounter++;
			}

			// !写内容
			for (CasdillyCustomer customer : customerList) {

				row = sheet.createRow(rowCounter);

				Map<Integer, String> ms = getMeasureString(customer.getScandata(),
						clothesTypeList.get(sheetCounter).getTypeName());
				String clothesSize = "";
				if (StringUtils.isEmpty(ms.get(2)) && StringUtils.isEmpty(ms.get(3))) {
				} else {
					clothesSize = getClothesString(csdMap, clothesTypeList.get(sheetCounter).getTypeName(),
							StringUtils.isEmpty(ms.get(2)) ? ms.get(3) : ms.get(2));

				}

				for (int cellCounter = 0; cellCounter < tableHeaderList.size(); cellCounter++) {

					cell = row.createCell(cellCounter);
					// {"编号","姓名","性别","年龄","公司","部门","电话","上衣号衣","下衣号衣","单位","净体尺寸","成衣尺寸","修正量","备注","正面照","背面照","侧面照","客户签名"};
					if (cellCounter == 0)
						cell.setCellValue(
								customer.getCustomerIndex() == null ? "" : customer.getCustomerIndex().toString());// 编号
					else if (cellCounter == 1)
						cell.setCellValue(customer.getCustomerName());// 姓名
					else if (cellCounter == 2)
						cell.setCellValue(customer.getCustomerSex() == 0 ? "男" : "女");// 性别
					else if (cellCounter == 3)
						cell.setCellValue(customer.getCustomerAge() == null ? "" : customer.getCustomerAge());// 年龄
					else if (cellCounter == 4)
						cell.setCellValue(customer.getCustomerCom() == null ? "" : customer.getCustomerCom());// 公司
					else if (cellCounter == 5)
						cell.setCellValue(customer.getCustomerDep() == null ? "" : customer.getCustomerDep());// 部门
					else if (cellCounter == 6)
						cell.setCellValue(customer.getCustomerTel() == null ? "" : customer.getCustomerTel());// 电话
					else if (cellCounter == 7)
						cell.setCellValue(ms.get(2));// 上衣号衣
					else if (cellCounter == 8)
						cell.setCellValue(ms.get(3));// 下衣号衣
					else if (cellCounter == 9)
						cell.setCellValue("厘米");// 单位
					else if (cellCounter == 10)
						cell.setCellValue(ms.get(0));// 净体尺寸
					else if (cellCounter == 11)
						cell.setCellValue(clothesSize);// 成衣尺寸
					else if (cellCounter == 12)
						cell.setCellValue(ms.get(1));// 修正量
					else if (cellCounter == 13)
						cell.setCellValue(customer.getCustomerBeiZhu() == null ? "" : customer.getCustomerBeiZhu());// 备注

					else if (cellCounter == 14 && !StringUtils.isEmpty(customer.getcPhotoZM())) {
						cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
						cell.setCellFormula("HYPERLINK(\"" + customer.getcPhotoZM() + "\",\"" + "点击查看照片" + "\")");

					} else if (cellCounter == 15 && !StringUtils.isEmpty(customer.getcPhotoBM())) {
						cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
						cell.setCellFormula("HYPERLINK(\"" + customer.getcPhotoBM() + "\",\"" + "点击查看照片" + "\")");

					}

					else if (cellCounter == 16 && !StringUtils.isEmpty(customer.getcPhotoCM())) {
						cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
						cell.setCellFormula("HYPERLINK(\"" + customer.getcPhotoCM() + "\",\"" + "点击查看照片" + "\")");

					} else if (cellCounter == 17 && !StringUtils.isEmpty(customer.getcPhotoQM())) {
						cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
						cell.setCellFormula("HYPERLINK(\"" + customer.getcPhotoQM() + "\",\"" + "点击查看照片" + "\")");

					}

				}
				rowCounter++;
			}

		}
		return hssfWorkbook;
	}

	/**
	 * 根据成衣号型返回成衣数值数据字符串
	 * 
	 * @param csdMap
	 *            成衣数据集合
	 * @param typeName
	 *            品类名
	 * @param sizekey
	 *            成衣号型
	 * @return 返回当前成衣号型数据字符串
	 */
	private String getClothesString(HashMap<String, Object> csdMap, String typeName, String sizekey) {

		String result = "";
		List<Map> csdList = (List<Map>) csdMap.get(typeName);
		if (ListUtils.isSubstantial(csdList)) {
			for (Map map : csdList) {
				if (map.get("sizekey").toString().equals(sizekey)) {

					for (Object object : map.keySet()) {
						if (!(object.equals("sizeid") || object.equals("sizekey") || object.equals("csName")
								|| object.equals("gender"))) {
							result += !StringUtils.isEmpty((String) map.get(object))
									? object + map.get(object).toString() + ","
									: "";
						}

					}
				}
			}
		}

		return result;
	}

	/**
	 * 用户对象进来，测量数据串出去
	 * 
	 * @param scandata
	 * @param typeName
	 * @return resultMap.put(0,itemStr); <br>
	 *         resultMap.put(1,adjustStr); <br>
	 *         resultMap.put(2,人工上衣号型); <br>
	 *         resultMap.put(3,人工下裤号型);
	 * 
	 */
	private Map<Integer, String> getMeasureString(List<CasdillyScanData> scandata, String typeName) {

		Map<Integer, String> resultMap = new HashMap<Integer, String>();
		String itemStr = "";
		String adjustStr = "";

		if (ListUtils.isNullOrEmpty(scandata)) {
			resultMap.put(0, itemStr);
			resultMap.put(1, adjustStr);

			return resultMap;
		}

		for (CasdillyScanData casdillyScanData : scandata) {

			if (casdillyScanData.getCategory().equals(typeName)) {
				String[] shuzhiArr = casdillyScanData.getShuzhi().split("_");
				if (!casdillyScanData.getTypename().equals("人工上衣号型") && !casdillyScanData.getTypename().equals("人工下裤号型")
						&& !casdillyScanData.getTypename().equals("自动上衣号型")
						&& !casdillyScanData.getTypename().equals("自动下裤号型")) {
					itemStr += casdillyScanData.getTypename() + shuzhiArr[0] + ","; // 净体串
				}
				if (casdillyScanData.getTypename().equals("人工上衣号型")) {
					resultMap.put(2, casdillyScanData.getShuzhi());
				}

				if (casdillyScanData.getTypename().equals("人工下裤号型")) {
					resultMap.put(3, casdillyScanData.getShuzhi());
				}

				if (shuzhiArr.length == 2 && !shuzhiArr[1].equals("0")) {
					adjustStr += casdillyScanData.getTypename() + shuzhiArr[1] + ","; // 调整串
				}
			}

		}

		resultMap.put(0, itemStr);
		resultMap.put(1, adjustStr);

		return resultMap;
	}

	@ResponseBody
	@RequestMapping(value = "/page.hodo_exportCheckedData.ashx")
	public void hodoExportCheckedData(String ids, String hetongSerial, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// 品类信息
		List<ClothesType> clothesTypeList = clothesTypeService.findByTypeCPIDSerial(hetongSerial);

		// 成衣信息
		HashMap<String, Object> csdMap = new HashMap<String, Object>();

		for (ClothesType clothesType : clothesTypeList) {

			if (null != clothesType.getClothesSizeID()) {
				List<Map<String, String>> csdList = csService.findByClothesSizeID(clothesType.getClothesSizeID());
				csdMap.put(clothesType.getTypeName(), csdList);
			}

		}

		/*
		 * //获取用户信息 和测量数据信息 List<CasdillyCustomer> customerList =
		 * customerService.hodoListByHetongSerial(customer);
		 */
		// ！准备内容数据
		List<CasdillyCustomer> customerList = customerService.hodoListByIDs(ids);

		// ！准备表头数据
		String[] tableHeaderArray = { "编号", "姓名", "性别", "年龄", "公司", "部门", "电话", "上衣号衣", "下衣号衣", "单位", "净体尺寸", "成衣尺寸",
				"修正量", "备注", "正面照", "背面照", "侧面照", "客户签名" };
		ArrayList<String> tableHeaderList = new ArrayList<String>(Arrays.asList(tableHeaderArray));

		// 初始化excel
		HSSFWorkbook initExcel = initExcel(tableHeaderList, customerList, clothesTypeList, csdMap);

		// ! 5、将Excel 保存到硬盘

		String linuxPartName = "选中用户_由";

		String filePath = exportPath + linuxPartName + this.getSessionStaff().getsName() + "于"
				+ new SimpleDateFormat("YYYY年MM月dd日HH时mm分").format(new Date()) + "导出.xls";
		String os = System.getProperty("os.name");
		if (os.toLowerCase().startsWith("win")) {
			String partName = "选中用户】_【";
			filePath = StringUtils.GetRootPath(request) + "/home/bwhx/package/huamingcexls/【" + hetongSerial + partName
					+ this.getSessionStaff().getsName() + "】_【"
					+ new SimpleDateFormat("YYYY年MM月dd日HH时mm分ss秒").format(new Date()) + "】.xls";

		}

		FileOutputStream fileOutputStream = new FileOutputStream(filePath);

		initExcel.write(fileOutputStream);
		fileOutputStream.close();

		File file = new File(filePath);
		String filename = file.getName();
		// 以流的形式下载文件。
		InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
		byte[] buffer = new byte[fis.available()];
		fis.read(buffer);
		fis.close();

		response.reset();
		// 设置response的Header
		String string = new String(filename.getBytes());
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
		response.addHeader("Content-Length", "" + file.length());
		OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		toClient.write(buffer);
		toClient.flush();
		toClient.close();
		// TODO
		// customerService.updateCustomerExportStatus(list,this.getSessionStaff().getsId(),new
		// Date());
	}

	@ResponseBody
	@RequestMapping(value = "/page.everyone.hodo_exportdata_body.ashx")
	public void HodoExportdataBody(CasdillyCustomer customer, HttpServletResponse response, HttpServletRequest request)
			throws FileNotFoundException, IOException {

		// 解决参数乱码问题
		String customerName = request.getParameter("customerName");
		if (!StringUtils.isEmpty(customerName)) {

			customerName = java.net.URLDecoder.decode(request.getParameter("customerName"), "UTF-8");
			customer.setCustomerName(customerName);
		}

		Staff sessionStaff = this.getSessionStaff();
		if (null == sessionStaff.getUserType() || 1 != sessionStaff.getUserType()) {
			customer.setCreatorID(sessionStaff.getsId().toString());
		}

		// 获取品类信息，成衣信息

		// 品类信息
		List<ClothesType> clothesTypeList = clothesTypeService.findByTypeCPIDSerial(customer.getHetongSerial());

		// 成衣信息
		/*
		 * HashMap<String, Object> csdMap = new HashMap<String, Object>();
		 * 
		 * for (ClothesType clothesType : clothesTypeList) {
		 * 
		 * if(null != clothesType.getClothesSizeID()){ List<Map<String, String>> csdList
		 * = csService.findByClothesSizeID(clothesType.getClothesSizeID());
		 * csdMap.put(clothesType.getTypeName(), csdList); }
		 * 
		 * }
		 */

		// 获取用户信息 和测量数据信息
		List<CasdillyCustomer> customerList = customerService.hodoListByHetongSerial(customer);

		// ！准备表头数据
		String[] tableHeaderArrayBaseInfo = { "编号", "姓名", "性别", "年龄", "公司", "部门", "电话", "单位" };
		String[] tableHeaderArrayClothesTypeInfo = {};
		// String[] tableHeaderArrayTailInfo = {"修正量","备注","正面照","背面照","侧面照","客户签名"};
		String[] tableHeaderArrayTailInfo = { "正面照", "背面照", "侧面照", "客户签名", "测量师" };

		// 初始化excel
		HSSFWorkbook initExcel = initBodyExcel(clothesTypeList, tableHeaderArrayBaseInfo,
				tableHeaderArrayClothesTypeInfo, tableHeaderArrayTailInfo, customerList);

		// 获取图片资料并压缩

		// response 返回

		// ! 5、将Excel 保存到硬盘

		String linuxPartName = "净体数据_全部用户_由";

		if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_1")) {
			linuxPartName = "净体数据_已量用户_由";

		} else if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_null")) {
			linuxPartName = "未量用户_由";
		}

		String filePath = exportPath + customer.getHetongSerial() + linuxPartName + this.getSessionStaff().getsName()
				+ "于" + new SimpleDateFormat("YYYY年MM月dd日HH时mm分").format(new Date()) + "导出.xls";
		String os = System.getProperty("os.name");
		if (os.toLowerCase().startsWith("win")) {
			String partName = "净体数据_全部用户】_【";

			if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_1")) {
				partName = "净体数据_已量用户】_【";

			} else if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_null")) {
				partName = "未量用户】_【";
			}
			filePath = StringUtils.GetRootPath(request) + "/home/bwhx/package/huamingcexls/【"
					+ customer.getHetongSerial() + partName + this.getSessionStaff().getsName() + "】_【"
					+ new SimpleDateFormat("YYYY年MM月dd日HH时mm分ss秒").format(new Date()) + "】.xls";

		}
		FileOutputStream fileOutputStream = new FileOutputStream(filePath);

		initExcel.write(fileOutputStream);
		fileOutputStream.close();

		File file = new File(filePath);
		String filename = file.getName();
		// 以流的形式下载文件。
		InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
		byte[] buffer = new byte[fis.available()];
		fis.read(buffer);
		fis.close();

		response.reset();
		// 设置response的Header
		String string = new String(filename.getBytes());
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
		response.addHeader("Content-Length", "" + file.length());
		OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		toClient.write(buffer);
		toClient.flush();
		toClient.close();
		// TODO
		// customerService.updateCustomerExportStatus(customerList,this.getSessionStaff().getsId(),new
		// Date());
	}

	/**
	 * 导出净体数据
	 * 
	 * @param clothesTypeList
	 *            品类对象List
	 * @param tableHeaderArrayBaseInfo
	 *            客户基本信息表头
	 * @param tableHeaderArrayClothesTypeInfo
	 *            品类表头,是空的，先传进来
	 * @param tableHeaderArrayTailInfo
	 *            尾巴表头，备注、相片等
	 * @param customerList
	 *            用户信息和测量数据信息List
	 * @return
	 */
	private HSSFWorkbook initBodyExcel(List<ClothesType> clothesTypeList, String[] tableHeaderArrayBaseInfo,
			String[] tableHeaderArrayClothesTypeInfo, String[] tableHeaderArrayTailInfo,
			List<CasdillyCustomer> customerList) {

		ArrayList<String> clothesTypeNameList = new ArrayList<String>();
		for (int i = 0; i < clothesTypeList.size(); i++) {
			if (clothesTypeList.get(i).getTypeName().equals("公共尺寸")) {
				continue;
			}
			clothesTypeNameList.add(clothesTypeList.get(i).getTypeName());
		}

		HSSFWorkbook hssfWorkbook = new HSSFWorkbook();// 1、 工作薄 （Excel文档 ）

		for (int sheetCounter = 0; sheetCounter < clothesTypeList.size(); sheetCounter++) {

			ArrayList<String> tableHeaderList = new ArrayList<String>();

			// ！初始化excel表，

			// 组装表头
			String typeItem = clothesTypeList.get(sheetCounter).getTypeItemsName() + ",备注";
			tableHeaderArrayClothesTypeInfo = typeItem.split(",");
			tableHeaderList.addAll(Arrays.asList(tableHeaderArrayBaseInfo));
			tableHeaderList.addAll(Arrays.asList(tableHeaderArrayClothesTypeInfo));
			tableHeaderList.addAll(clothesTypeNameList);
			tableHeaderList.addAll(Arrays.asList(tableHeaderArrayTailInfo));

			String typeName = clothesTypeList.get(sheetCounter).getTypeName();
			if (!typeName.equals("公共尺寸")) {
				continue;
			}
			// HSSFSheet sheet = hssfWorkbook.createSheet(typeName);// 2、写一个sheet
			HSSFSheet sheet = hssfWorkbook.createSheet("数据");// 2、写一个sheet
			sheet.setColumnWidth(4, 13 * 2 * 256);
			sheet.setColumnWidth(6, 6 * 2 * 256);
			/*
			 * sheet.setColumnWidth(9+tableHeaderArrayClothesTypeInfo.length+1,30*2*256);//
			 * 修正量
			 * sheet.setColumnWidth(9+tableHeaderArrayClothesTypeInfo.length+2,20*2*256);//
			 * 备注
			 * sheet.setColumnWidth(9+tableHeaderArrayClothesTypeInfo.length+3,7*2*256);//正面
			 * sheet.setColumnWidth(9+tableHeaderArrayClothesTypeInfo.length+4,7*2*256);//正面
			 * sheet.setColumnWidth(9+tableHeaderArrayClothesTypeInfo.length+5,7*2*256);//正面
			 * sheet.setColumnWidth(9+tableHeaderArrayClothesTypeInfo.length+6,7*2*256);//正面
			 */ HSSFRow row = null; // 3、定义row
			HSSFCell cell = null; // 4、 定义cell
			int rowCounter = 0;

			if (rowCounter == 0) {
				row = sheet.createRow(rowCounter);
				for (int cellCounter = 0; cellCounter < tableHeaderList.size(); cellCounter++) {
					cell = row.createCell(cellCounter);
					cell.setCellValue(tableHeaderList.get(cellCounter));

				}
				rowCounter++;
			}

			// !写内容
			for (CasdillyCustomer customer : customerList) {

				row = sheet.createRow(rowCounter);

				// Map<Integer,String> ms =
				// getMeasureString(customer.getScandata(),clothesTypeList.get(sheetCounter).getTypeName());
				/*
				 * String clothesSize="";
				 * if(StringUtils.isEmpty(ms.get(2))&&StringUtils.isEmpty(ms.get(3))) {}else{
				 * clothesSize =
				 * getClothesString(csdMap,clothesTypeList.get(sheetCounter).getTypeName(),
				 * StringUtils.isEmpty(ms.get(2))?ms.get(3):ms.get(2));
				 * 
				 * }
				 */

				HashMap<String, String> bodySizeMap = getBodySizeMap(customer.getScandata(),
						clothesTypeList.get(sheetCounter).getTypeName());

				for (int cellCounter = 0; cellCounter < tableHeaderList.size(); cellCounter++) {
					if (cellCounter > 9 && cellCounter <= 9 + tableHeaderArrayClothesTypeInfo.length) {
						continue;// 啥都不做，单独处理
					}

					cell = row.createCell(cellCounter);
					// {"编号","姓名","性别","年龄","公司","部门","电话","上衣号衣","下衣号衣","单位","净体尺寸","成衣尺寸","修正量","备注","正面照","背面照","侧面照","客户签名"};
					if (cellCounter == 0)
						cell.setCellValue(
								customer.getCustomerIndex() == null ? "" : customer.getCustomerIndex().toString());// 编号
					else if (cellCounter == 1)
						cell.setCellValue(customer.getCustomerName());// 姓名
					else if (cellCounter == 2 && customer.getCustomerSex() != null)
						cell.setCellValue(customer.getCustomerSex() == 0 ? "男" : "女");// 性别
					else if (cellCounter == 3)
						cell.setCellValue(customer.getCustomerAge() == null ? "" : customer.getCustomerAge());// 年龄
					else if (cellCounter == 4)
						cell.setCellValue(customer.getCustomerCom() == null ? "" : customer.getCustomerCom());// 公司
					else if (cellCounter == 5)
						cell.setCellValue(customer.getCustomerDep() == null ? "" : customer.getCustomerDep());// 部门
					else if (cellCounter == 6)
						cell.setCellValue(customer.getCustomerTel() == null ? "" : customer.getCustomerTel());// 电话
					// else if(cellCounter==7) cell.setCellValue(ms.get(2));//上衣号衣
					// else if(cellCounter==8) cell.setCellValue(ms.get(3));//下衣号衣
					else if (cellCounter == 7)
						cell.setCellValue("厘米");// 单位

					// {"修正量","备注","正面照","背面照","侧面照","客户签名"};
					// else
					// if(cellCounter==9+tableHeaderArrayClothesTypeInfo.length+clothesTypeNameList.size()+1)
					// cell.setCellValue(ms.get(1));//修正量
					/*
					 * else
					 * if(cellCounter==9+tableHeaderArrayClothesTypeInfo.length+clothesTypeNameList.
					 * size()+2){
					 * cell.setCellValue(StringUtils.isEmpty(bodySizeMap.get("备注"))?"":bodySizeMap.
					 * get("备注")); }
					 */
					else if (cellCounter == 7 + tableHeaderArrayClothesTypeInfo.length + clothesTypeNameList.size() + 1
							&& !StringUtils.isEmpty(customer.getcPhotoZM())) {
						cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
						cell.setCellFormula("HYPERLINK(\"" + customer.getcPhotoZM() + "\",\"" + "点击查看照片" + "\")");

					} else if (cellCounter == 7 + tableHeaderArrayClothesTypeInfo.length + clothesTypeNameList.size()
							+ 2 && !StringUtils.isEmpty(customer.getcPhotoBM())) {
						cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
						cell.setCellFormula("HYPERLINK(\"" + customer.getcPhotoBM() + "\",\"" + "点击查看照片" + "\")");

					}

					else if (cellCounter == 7 + tableHeaderArrayClothesTypeInfo.length + clothesTypeNameList.size() + 3
							&& !StringUtils.isEmpty(customer.getcPhotoCM())) {
						cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
						cell.setCellFormula("HYPERLINK(\"" + customer.getcPhotoCM() + "\",\"" + "点击查看照片" + "\")");

					} else if (cellCounter == 7 + tableHeaderArrayClothesTypeInfo.length + clothesTypeNameList.size()
							+ 4 && !StringUtils.isEmpty(customer.getcPhotoQM())) {
						cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
						cell.setCellFormula("HYPERLINK(\"" + customer.getcPhotoQM() + "\",\"" + "点击查看照片" + "\")");

					} else if (cellCounter == 7 + tableHeaderArrayClothesTypeInfo.length + clothesTypeNameList.size()
							+ 5 && !StringUtils.isEmpty(customer.getUploaderID())) {

						String name = staffService.getName(customer.getUploaderID());
						cell.setCellValue(name);// 量体师id

					}

				}

				for (int i = 1; i < tableHeaderArrayClothesTypeInfo.length + 1; i++) {
					cell = row.createCell(7 + i);
					String bodySize = bodySizeMap.get(tableHeaderArrayClothesTypeInfo[i - 1]);
					cell.setCellValue(StringUtils.isEmpty(bodySize) ? "" : bodySize.split("_")[0]);

				}

				for (int i = 1; i < clothesTypeNameList.size() + 1; i++) {
					cell = row.createCell(7 + tableHeaderArrayClothesTypeInfo.length + i);
					/*
					 * String bodySize = bodySizeMap.get(tableHeaderArrayClothesTypeInfo[i-1]);
					 * cell.setCellValue(StringUtils.isEmpty(bodySize)?"":bodySize.split("_")[0]);
					 */

					String ctName = clothesTypeNameList.get(i - 1);
					List<CasdillyScanData> scandataList = customer.getScandata();
					for (CasdillyScanData scandata : scandataList) {
						if (!StringUtils.isEmpty(scandata.getCategory()) && !StringUtils.isEmpty(scandata.getTypename())
								&& scandata.getCategory().equals(ctName) && scandata.getTypename().equals("备注")) {
							cell.setCellValue(StringUtils.isEmpty(scandata.getShuzhi()) ? "" : scandata.getShuzhi());
						}
					}

				}

				rowCounter++;
			}

		}
		return hssfWorkbook;

	}

	private HashMap<String, String> getBodySizeMap(List<CasdillyScanData> scandata, String typeName) {

		HashMap<String, String> resultMap = new HashMap<String, String>();

		for (CasdillyScanData casdillyScanData : scandata) {
			if (casdillyScanData.getCategory().equals(typeName)) {
				resultMap.put(casdillyScanData.getTypename(), casdillyScanData.getShuzhi());

			}
		}
		return resultMap;
	}

	@ResponseBody
	@RequestMapping("/delCustomer.ashx")
	public HashMap<String, Object> delCustomer(HttpServletRequest request) {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();

		try {
			customerService.delCustomer((String) request.getAttribute("customerID"),
					(String) request.getAttribute("loginID"));

			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.MSG, Constant.MSG_SUCCESS);
		} catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			resultMap.put(Constant.MSG, Constant.MSG_FAIL);
		}

		return resultMap;

	}

	@ResponseBody
	@RequestMapping(value = "/page.everyone.hodo_exportdata_clothes.ashx")
	public void HodoExportdataClothes(CasdillyCustomer customer, HttpServletResponse response,
			HttpServletRequest request) throws FileNotFoundException, IOException {
		// 解决参数乱码问题
		String customerName = request.getParameter("customerName");
		if (!StringUtils.isEmpty(customerName)) {

			customerName = java.net.URLDecoder.decode(request.getParameter("customerName"), "UTF-8");
			customer.setCustomerName(customerName);
		}

		Staff sessionStaff = this.getSessionStaff();
		if (null == sessionStaff.getUserType() || 1 != sessionStaff.getUserType()) {
			customer.setCreatorID(sessionStaff.getsId().toString());
		}

		// 获取品类信息，成衣信息

		// 品类信息
		List<ClothesType> clothesTypeList = clothesTypeService.findByTypeCPIDSerial(customer.getHetongSerial());

		// 成衣信息
		HashMap<String, Object> csdMap = new HashMap<String, Object>();

		for (ClothesType clothesType : clothesTypeList) {

			if (null != clothesType.getClothesSizeID()) {
				List<Map<String, String>> csdList = csService.findByClothesSizeID(clothesType.getClothesSizeID());
				csdMap.put(clothesType.getTypeName(), csdList);
			}

		}

		// 获取用户信息 和测量数据信息
		List<CasdillyCustomer> customerList = customerService.hodoListByHetongSerial(customer);

		// ！准备表头数据
		String[] tableHeaderArrayBaseInfo = { "编号", "姓名", "性别", "年龄", "公司", "部门", "电话", "上衣号衣", "下衣号衣", "单位" };
		String[] tableHeaderArrayClothesTypeInfo = {};
		String[] tableHeaderArrayTailInfo = { "备注", "正面照", "背面照", "侧面照", "客户签名" };

		// 初始化excel
		HSSFWorkbook initExcel = initClothesExcel(clothesTypeList, tableHeaderArrayBaseInfo,
				tableHeaderArrayClothesTypeInfo, tableHeaderArrayTailInfo, customerList, csdMap);

		// 获取图片资料并压缩

		// response 返回

		// ! 5、将Excel 保存到硬盘

		String linuxPartName = "_成衣数据_全部用户_由";

		if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_1")) {
			linuxPartName = "_成衣数据_已量用户_由";

		} else if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_null")) {
			linuxPartName = "未量用户_由";
		}

		String filePath = exportPath + customer.getHetongSerial() + linuxPartName + this.getSessionStaff().getsName()
				+ "于" + new SimpleDateFormat("YYYY年MM月dd日HH时mm分").format(new Date()) + "导出.xls";
		String os = System.getProperty("os.name");
		if (os.toLowerCase().startsWith("win")) {

			String partName = "_成衣数据_全部用户】_【";

			if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_1")) {
				partName = "_成衣数据_已量用户】_【";

			} else if (null != customer.getcMeasureState() && customer.getcMeasureState().equals("is_null")) {
				partName = "未量用户】_【";
			}
			filePath = StringUtils.GetRootPath(request) + "/home/bwhx/package/huamingcexls/【"
					+ customer.getHetongSerial() + partName + this.getSessionStaff().getsName() + "】_【"
					+ new SimpleDateFormat("YYYY年MM月dd日HH时mm分ss秒").format(new Date()) + "】.xls";

		}
		FileOutputStream fileOutputStream = new FileOutputStream(filePath);

		initExcel.write(fileOutputStream);
		fileOutputStream.close();

		File file = new File(filePath);
		String filename = file.getName();
		// 以流的形式下载文件。
		InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
		byte[] buffer = new byte[fis.available()];
		fis.read(buffer);
		fis.close();

		response.reset();
		// 设置response的Header
		String string = new String(filename.getBytes());
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
		response.addHeader("Content-Length", "" + file.length());
		OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		toClient.write(buffer);
		toClient.flush();
		toClient.close();
		// TODO
		// customerService.updateCustomerExportStatus(customerList,this.getSessionStaff().getsId(),new
		// Date());
	}

	/**
	 * 返回成衣数据XLS表
	 * 
	 * @param clothesTypeList
	 *            品类列表
	 * @param tableHeaderArrayBaseInfo
	 *            用户基本信息表头
	 * @param tableHeaderArrayClothesTypeInfo
	 *            品类表头
	 * @param tableHeaderArrayTailInfo
	 *            左侧末尾表头
	 * @param customerList
	 *            用户列表
	 * @param csdMap
	 *            成衣尺寸map
	 * @return 返回成衣数据XLS表
	 */
	private HSSFWorkbook initClothesExcel(List<ClothesType> clothesTypeList, String[] tableHeaderArrayBaseInfo,
			String[] tableHeaderArrayClothesTypeInfo, String[] tableHeaderArrayTailInfo,
			List<CasdillyCustomer> customerList, HashMap<String, Object> csdMap) {

		HSSFWorkbook hssfWorkbook = new HSSFWorkbook();// 1、 工作薄 （Excel文档 ）

		for (int sheetCounter = 0; sheetCounter < clothesTypeList.size(); sheetCounter++) {

			ArrayList<String> tableHeaderList = new ArrayList<String>();

			// ！初始化excel表，

			// 组装表头
			String typeItem = clothesTypeList.get(sheetCounter).getTypeItemsName();
			tableHeaderArrayClothesTypeInfo = typeItem.split(",");
			tableHeaderList.addAll(Arrays.asList(tableHeaderArrayBaseInfo));
			tableHeaderList.addAll(Arrays.asList(tableHeaderArrayClothesTypeInfo));
			tableHeaderList.addAll(Arrays.asList(tableHeaderArrayTailInfo));

			String typeName = clothesTypeList.get(sheetCounter).getTypeName();
			HSSFSheet sheet = hssfWorkbook.createSheet(typeName);// 2、写一个sheet
			sheet.setColumnWidth(4, 13 * 2 * 256);
			sheet.setColumnWidth(6, 6 * 2 * 256);
			sheet.setColumnWidth(9 + tableHeaderArrayClothesTypeInfo.length + 1, 30 * 2 * 256);// 修正量
			sheet.setColumnWidth(9 + tableHeaderArrayClothesTypeInfo.length + 2, 20 * 2 * 256);// 备注
			sheet.setColumnWidth(9 + tableHeaderArrayClothesTypeInfo.length + 3, 7 * 2 * 256);// 正面
			sheet.setColumnWidth(9 + tableHeaderArrayClothesTypeInfo.length + 4, 7 * 2 * 256);// 正面
			sheet.setColumnWidth(9 + tableHeaderArrayClothesTypeInfo.length + 5, 7 * 2 * 256);// 正面
			sheet.setColumnWidth(9 + tableHeaderArrayClothesTypeInfo.length + 6, 7 * 2 * 256);// 正面
			HSSFRow row = null; // 3、定义row
			HSSFCell cell = null; // 4、 定义cell
			int rowCounter = 0;

			if (rowCounter == 0) {
				row = sheet.createRow(rowCounter);
				for (int cellCounter = 0; cellCounter < tableHeaderList.size(); cellCounter++) {
					cell = row.createCell(cellCounter);
					cell.setCellValue(tableHeaderList.get(cellCounter));

				}
				rowCounter++;
			}

			// !写内容
			for (CasdillyCustomer customer : customerList) {

				row = sheet.createRow(rowCounter);

				Map<Integer, String> ms = getMeasureString(customer.getScandata(),
						clothesTypeList.get(sheetCounter).getTypeName());
				HashMap<String, String> clothesSizeMap = new HashMap<String, String>();
				if (StringUtils.isEmpty(ms.get(2)) && StringUtils.isEmpty(ms.get(3))) {
				} else {
					clothesSizeMap = getThisClothesSizeMap(csdMap, clothesTypeList.get(sheetCounter).getTypeName(),
							StringUtils.isEmpty(ms.get(2)) ? ms.get(3) : ms.get(2), customer.getCustomerSex());

				}

				HashMap<String, String> bodySizeMap = new HashMap<String, String>();
				HashMap<String, String> adjustClothesSizeMap = new HashMap<String, String>();

				bodySizeMap = getBodySizeMap(customer.getScandata(), clothesTypeList.get(sheetCounter).getTypeName());

				Set<String> keySet = bodySizeMap.keySet();
				for (String key : keySet) {
					String value = bodySizeMap.get(key);
					String[] valueSplitArr = value.split("_");
					String adjust = valueSplitArr.length == 2 ? valueSplitArr[1] : null;
					if (!StringUtils.isEmpty(adjust) && !adjust.equals("0")) {
						adjustClothesSizeMap.put(key, adjust);
					}

					if (key.equals("身高") || key.equals("紧胸围") || key.equals("紧臀围") || key.equals("体重")) {
						clothesSizeMap.put(key, value.split("_")[0]);
					}

				}
				Set<String> adjustClothesSizeMapKeySet = adjustClothesSizeMap.keySet();
				for (String key : adjustClothesSizeMapKeySet) {
					String standardClothesSize = clothesSizeMap.get(key);
					String adjustSize = adjustClothesSizeMap.get(key);
					System.out.println(key + standardClothesSize);
					if (!StringUtils.isEmpty(standardClothesSize)) {
						BigDecimal scs = new BigDecimal(standardClothesSize);
						BigDecimal as = new BigDecimal(adjustSize);
						BigDecimal standardAddAdjust = scs.add(as);
						clothesSizeMap.put(key, standardAddAdjust.toString());
					}
				}

				for (int cellCounter = 0; cellCounter < tableHeaderList.size(); cellCounter++) {
					if (cellCounter > 9 && cellCounter <= 9 + tableHeaderArrayClothesTypeInfo.length) {
						continue;// 啥都不做，单独处理
					}

					cell = row.createCell(cellCounter);
					// {"编号","姓名","性别","年龄","公司","部门","电话","上衣号衣","下衣号衣","单位","净体尺寸","成衣尺寸","修正量","备注","正面照","背面照","侧面照","客户签名"};
					if (cellCounter == 0)
						cell.setCellValue(
								customer.getCustomerIndex() == null ? "" : customer.getCustomerIndex().toString());// 编号
					else if (cellCounter == 1)
						cell.setCellValue(customer.getCustomerName());// 姓名
					else if (cellCounter == 2)
						cell.setCellValue(customer.getCustomerSex() == 0 ? "男" : "女");// 性别
					else if (cellCounter == 3)
						cell.setCellValue(customer.getCustomerAge() == null ? "" : customer.getCustomerAge());// 年龄
					else if (cellCounter == 4)
						cell.setCellValue(customer.getCustomerCom() == null ? "" : customer.getCustomerCom());// 公司
					else if (cellCounter == 5)
						cell.setCellValue(customer.getCustomerDep() == null ? "" : customer.getCustomerDep());// 部门
					else if (cellCounter == 6)
						cell.setCellValue(customer.getCustomerTel() == null ? "" : customer.getCustomerTel());// 电话
					else if (cellCounter == 7)
						cell.setCellValue(ms.get(2));// 上衣号衣
					else if (cellCounter == 8)
						cell.setCellValue(ms.get(3));// 下衣号衣
					else if (cellCounter == 9)
						cell.setCellValue("厘米");// 单位

					// {"修正量","备注","正面照","背面照","侧面照","客户签名"};
					// else if(cellCounter==9+tableHeaderArrayClothesTypeInfo.length+1)
					// cell.setCellValue(ms.get(1));//修正量
					else if (cellCounter == 9 + tableHeaderArrayClothesTypeInfo.length + 1)
						cell.setCellValue(customer.getCustomerBeiZhu() == null ? "" : customer.getCustomerBeiZhu());// 备注

					else if (cellCounter == 9 + tableHeaderArrayClothesTypeInfo.length + 2
							&& !StringUtils.isEmpty(customer.getcPhotoZM())) {
						cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
						cell.setCellFormula("HYPERLINK(\"" + customer.getcPhotoZM() + "\",\"" + "点击查看照片" + "\")");

					} else if (cellCounter == 9 + tableHeaderArrayClothesTypeInfo.length + 3
							&& !StringUtils.isEmpty(customer.getcPhotoBM())) {
						cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
						cell.setCellFormula("HYPERLINK(\"" + customer.getcPhotoBM() + "\",\"" + "点击查看照片" + "\")");

					}

					else if (cellCounter == 9 + tableHeaderArrayClothesTypeInfo.length + 4
							&& !StringUtils.isEmpty(customer.getcPhotoCM())) {
						cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
						cell.setCellFormula("HYPERLINK(\"" + customer.getcPhotoCM() + "\",\"" + "点击查看照片" + "\")");

					} else if (cellCounter == 9 + tableHeaderArrayClothesTypeInfo.length + 5
							&& !StringUtils.isEmpty(customer.getcPhotoQM())) {
						cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
						cell.setCellFormula("HYPERLINK(\"" + customer.getcPhotoQM() + "\",\"" + "点击查看照片" + "\")");

					}

				}

				for (int i = 1; i < tableHeaderArrayClothesTypeInfo.length + 1; i++) {
					cell = row.createCell(9 + i);
					String clothesSize = clothesSizeMap.get(tableHeaderArrayClothesTypeInfo[i - 1]);
					cell.setCellValue(StringUtils.isEmpty(clothesSize) ? "" : clothesSize);

				}

				rowCounter++;
			}

		}
		return hssfWorkbook;

	}

	/**
	 * 
	 * @param csdMap
	 * @param typeName
	 * @param sizekey
	 * @return
	 */
	private HashMap<String, String> getThisClothesSizeMap(HashMap<String, Object> csdMap, String typeName,
			String sizekey, Integer gender) {

		HashMap<String, String> clothesSizeMap = new HashMap<String, String>();

		String[] theHaoXing = sizekey.split("/");

		List<Map> csdList = (List<Map>) csdMap.get(typeName);
		if (ListUtils.isSubstantial(csdList)) {
			for (Map map : csdList) {
				if (((null != map.get("heightkey") && map.get("heightkey").equals(theHaoXing[0]))
						|| (null != map.get("widthkey") && map.get("widthkey").equals(theHaoXing[1])))
						&& (null != map.get("gender") && map.get("gender").equals(String.valueOf(gender)))

				) {

					for (Object object : map.keySet()) {
						if (null != map.get(object) && !StringUtils.isEmpty(object.toString().trim())) {
							// result += !StringUtils.isEmpty((String)map.get(object)) ?
							// object+map.get(object).toString()+",":"";

							clothesSizeMap.put(object.toString(), (String) map.get(object).toString());

						}

					}
				}
			}
		}

		return clothesSizeMap;

	}

}
